<script setup lang="ts">
	import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
	import { reactive, ref } from 'vue';
	import type { PaginationParam } from '@/api/model/pageParam';
	import type { shopQueryModel, shopModelArray, shopModel } from '@/api/model/shop.ts';
	import type { commonStatus } from '@/api/model/CommonStatus';
	import type { ResultModel } from '@/api/model/ResultModel';


	// 表格加载loading
	const loading = ref(true);
	// 控制对话框
	const dialogVisble = ref(false);
	const dialogAttribute = ref({ title: "" })
	// 查询参数
	const shopQueryData = ref<shopQueryModel>({
		username: "",
		shopManagerName: "",
		status: "",
		shopStatus: ""
	})

	const shopData = ref<shopModelArray>([])
	// 状态查询栏的查询数据
	const status_list = ref([
		{ "value": "1", "label": "正常" },
		{ "value": "0", "label": "禁用" }
	])

	const shop_status_list = ref([
		{ "value": "1", "label": "开铺" },
		{ "value": "0", "label": "闭铺" }
	])

	// 分页参数
	const pagination = ref<PaginationParam>({
		currentPage: 1,   //当前页码
		pageSize: 10,      //每页记录数
		total: 0         //总条数
	})

	const handleSizeChange = (pageSize : number) => {
		pagination.value.pageSize = pageSize;
		getShopList()
	}

	const handleCurrentChange = (page : number) => {
		pagination.value.currentPage = page;
		getShopList()
	}

	// 分页条件查询的内容框架
	const conditionList = reactive([
		{
			id: 1,
			type: "input",
			label: "店铺名",
			prop: "shopName",
			placeholder: "请输入查询的店铺名",
			span: 6,
		},
		{
			id: 2,
			type: "input",
			label: "店长",
			prop: "shopManagerName",
			placeholder: "请输入查询的店长",
			span: 6,
		},
		{
			id: 3,
			type: "select",
			label: "店铺状态",
			prop: "status",
			placeholder: "请选择",
			optionList: [
				{
					label: "禁用",
					value: "0",
				},
				{
					label: "正常",
					value: "1",
				},
			],
			span: 6,
		},
		{
			id: 4,
			type: "select",
			label: "店铺营业状态",
			prop: "shopStatus",
			placeholder: "请选择",
			optionList: [
				{
					label: "闭铺",
					value: "0",
				},
				{
					label: "开铺",
					value: "1",
				},
			],
			span: 6,
		},
	])

	// 存放表单校验数据
	const shopRef = ref<FormInstance>()
	// 清除表单校验的红字
	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}

	// 分页条件查询
	const getShopList = async () => {
		loading.value = true;
		const res = await queryShopListApi(shopQueryData.value.username, shopQueryData.value.shopManagerName, shopQueryData.value.status, shopQueryData.value.shopStatus, pagination.value.currentPage, pagination.value.pageSize)
		console.log(res);
		if (res.code) {
			shopData.value = res.data.list
			pagination.value.total = res.data.total
		}
		loading.value = false;
	}

	// 清空按钮
	const cleanSet = () => {
		shopQueryData.value.username = ''
		shopQueryData.value.shopManagerName = ''
		shopQueryData.value.status = ""
		shopQueryData.value.shopStatus = ''
		getShopList()
	}

	// --------------------------------------------新增店铺-------------------------------------------------
	const shops = ref<shopModel>({
		shopName: '',
		shopManagerId: '',
		shopManagerName: '',
		email: '',
		phoneNumber: '',
		// 默认是店铺关闭状态
		shopStatus: '0',
		businessHours: '',
		imgUrl: '',
		minOrderPrice: 0,
		deliveryFee: 0,
		rating: 0,
		monthSales: 0,
		createdTime: '',
		updatedTime: '',
		status: '',
		dishes: [],
	})

	// 新增时查询admin
	const searchAdmins = async (query, cb) => {
		if (!query) {
			cb([])
			return;
		}
		loading.value = true;
		try {
			const res = await request.get<ResultModel>('/api/admin/managers/search', {
				params: { keyword: query },
			});

			if (res.data.length > 0) {
				const results = res.data.map((manager) => ({
					value: manager.username,
					id: manager.id,
				}));
				cb(results);
			} else {
				cb([]);
			}
		} catch (error) {
			console.error('搜索店长失败:', error);
			cb([]);
		} finally {
			loading.value = false;
		}
	}

	//表单校验规则
	const rules = ref<FormRules>({
		username: [
			{ required: true, message: '用户名不能为空', trigger: 'blur' },
			{ min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
		],
		shopManagerName: [
			{ required: true, message: '店长姓名不能为空', trigger: 'blur' },
			{ min: 3, max: 10, message: '店长姓名长度在 3 到 10 个字符', trigger: 'blur' },
		],
		email: [
			{ required: true, message: '邮箱不能为空', trigger: 'blur' },
			{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
		],
		phoneNumber: [
			{ required: true, message: '手机号不能为空', trigger: 'blur' },
			{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
		],
		businessHours: [
			{ required: true, message: '营业时间不能为空', trigger: 'blur' },
			{
				pattern: /^([01]?[0-9]|2[0-3]):[0-5][0-9]-([01]?[0-9]|2[0-3]):[0-5][0-9]$/,
				message: '请输入正确的营业时间格式（如：9:00-22:00）',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback();
						return;
					}
					const [start, end] = value.split('-');
					if (start >= end) {
						callback(new Error('结束时间必须晚于开始时间'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		minOrderPrice: [
			{ required: true, message: '最低外卖单价不能为空', trigger: 'blur' },
			{
				type: 'number',
				message: '必须输入数字值',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (value < 0) {
						callback(new Error('最低外卖单价不能为负数'));
					} else if (value > 9999) {
						callback(new Error('金额过大，请确认输入是否正确'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		deliveryFee: [
			{ required: true, message: '起送费不能为空', trigger: 'blur' },
			{
				type: 'number',
				message: '必须输入数字值',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (value < 0) {
						callback(new Error('起送费不能为负数'));
					} else if (value > 999) {
						callback(new Error('起送费金额过大，请确认输入是否正确'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		status: [
			{ required: true, message: '店铺状态不能为空', trigger: 'change' },
		],
	})

	// 上传图片

	const handleAvatarSuccess : UploadProps['onSuccess'] = (
		response,
		uploadFile
	) => {
		console.log(response.data);
		shops.value.imgUrl = response.data
	}

	const beforeAvatarUpload : UploadProps['beforeUpload'] = (rawFile) => {
		if (!rawFile) {
			ElMessage.error("请传入图片文件！")
			return false;
		}
		if (!rawFile.type.startsWith('image/')) {
			ElMessage.error('文件格式不正确!')
			return false
		} else if (rawFile.size / 1024 / 1024 > 2) {
			ElMessage.error('文件大小不能超过2MB')
			return false
		}
		return true
	}

	// 关闭对话框事件
	const handleClose = () => {
		shops.value = {
			username: '',
			shopManagerName: '',
			email: '',
			phoneNumber: '',
			// 默认是店铺关闭状态
			shopStatus: '0',
			businessHours: '',
			imgUrl: '',
			minOrderPrice: 0,
			deliveryFee: 0,
			rating: 0,
			monthSales: 0,
			createdTime: '',
			updatedTime: '',
			status: '',
			dishes: [],
		}
		// console.log('对话框已关闭');
	};
	const dialogRef = ref()

	// 确认事件
	const handleSuccess = async (formEl : FormInstance | undefined) => {
		const isValid = await dialogRef.value?.validate(shopRef.value)
		if (!isValid) return
		let res = null
		if (shops.value.id) {
			// id 有值代表修改，
			res = await updateShopApi(shops.value)
		} else {
			// id没值代表新增
			res = await addShopApi(shops.value)
		}
		if (res.code) {
			ElMessage.success('操作成功')
			dialogVisble.value = false;
			getShopList()
		} else {
			ElMessage.error(res.msg)
		}
	};

	const addShop = () => {
		resetForm(shopRef.value)
		dialogVisble.value = true;
		dialogAttribute.value.title = '新增站长'
	}

	// -----------------------------编辑店铺信息-----------------------------------
	// 编辑用户回显
	const updateShop = async (id : number) => {
		resetForm(shopRef.value)
		console.log("当前店铺id:" + id);
		dialogVisble.value = true;
		dialogAttribute.value.title = '修改站长'
		const res = await getByIdShopApi(id);
		if (res.code) {
			shops.value = res.data
		}
	}

	// -----------------------------(批量)删除管理员信息-----------------------------------
	// 批量删除的ids
	const selectedIds = ref<(number | undefined)[]>([]);

	// 多选框多选
	const handleSelectionChange = (val : shopModel[]) => {
		selectedIds.value = val.map(element => { return element.id })
	}

	const deleteShop = async (id : string) => {
		console.log("当前要删除的店铺id：" + id);
		const res = await deleteShopApi(id);
		if (res.code) {
			ElMessage.success("删除成功");
			getShopList()
		} else {
			ElMessage.error("删除失败");
		}
	}

	const deleteBatchShop = async () => {
		console.log("当前要删除的店铺id：" + selectedIds.value);
		const res = await deleteShopApi(selectedIds.value.toString())
		if (res.code) {
			ElMessage.success("删除成功");
			getShopList()
		} else {
			ElMessage.error("删除失败");
		}
	}

	// -----------------------------禁用(启用)管理员-----------------------------------
	// 状态
	const ShopStatus = ref<commonStatus>({
		id: 0,
		status: ''
	})
	const disableShop = async (row : any) => {
		ShopStatus.value.id = row.id;
		ShopStatus.value.status = row.status
		// console.log("当前要禁用的用户：" + row.status);
		// console.log("当前要禁用的用户：" + row.id);
		console.log("当前要禁用的用户：" + ShopStatus.value);
		const res = await disableShopApi(ShopStatus.value);
		if (res.code) {
			if (row.status == "1") { ElMessage.warning("禁用成功，店铺已被禁用！！"); getShopList() }
			else {
				ElMessage.success("启用成功，店铺可以正常使用！！");
				getShopList()
			}
		} else {
			ElMessage.error("禁用失败");
		}
	}
</script>

<template>
	<h1>熊吃外卖平台店铺管理</h1>
	<div style="width: 95%;">
		<div>
			<ConditionBar v-model:searchParams="shopQueryData" @search="" @reset="cleanSet"
				:conditionList="conditionList" />
		</div>
		<Dialog v-model:dialogVisble="dialogVisble" v-model:dialogTitle="dialogAttribute.title" @close="handleClose"
			@success="handleSuccess" ref="dialogRef">
			<el-form :model="shops" :rules="rules" ref="shopRef" label-width="100px">
				<!-- 用户名 -->
				<el-form-item label="用户名" prop="shopName">
					<el-autocomplete v-model="shops.shopName" :fetch-suggestions="searchAdmins" placeholder="请输入店长用户名"
						clearable @select="handleSelectManager">
						<!-- 自定义下拉选项 -->
						<template #default="{ item }">
							<div>{{ item.value }}</div>
						</template>

						<!-- 无数据时显示提示 + 添加按钮 -->
						<template #prefix>
							<el-icon>
								<User />
							</el-icon>
						</template>

						<template #empty>
							<div class="empty-tip">
								<p>当前没有该店长，是否要添加？</p>
								<el-button type="primary" size="small" @click="addNewManager(shops.username)">
									添加
								</el-button>
							</div>
						</template>
					</el-autocomplete>
				</el-form-item>

				<!-- 店长姓名 -->
				<el-form-item label="店长姓名" prop="shopManagerName">
					<el-input v-model="shops.shopManagerName" placeholder="请输入店长姓名(3-10个字符)" />
				</el-form-item>

				<!-- 邮箱 -->
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="shops.email" placeholder="请输入邮箱" type="email" />
				</el-form-item>

				<!-- 手机号 -->
				<el-form-item label="手机号" prop="phoneNumber">
					<el-input v-model="shops.phoneNumber" placeholder="请输入11位手机号" maxlength="11" />
				</el-form-item>

				<!-- 营业时间 -->
				<el-form-item label="营业时间" prop="businessHours">
					<el-input v-model="shops.businessHours" placeholder="例如: 9:00-22:00" />
				</el-form-item>

				<!-- 最低外卖单价 -->
				<el-form-item label="最低外卖单价" prop="minOrderPrice">
					<el-input v-model.number="shops.minOrderPrice" placeholder="请输入金额(0-9999)" type="number">
						<template #append>元</template>
					</el-input>
				</el-form-item>

				<!-- 起送费 -->
				<el-form-item label="起送费" prop="deliveryFee">
					<el-input v-model.number="shops.deliveryFee" placeholder="请输入金额(0-999)" type="number">
						<template #append>元</template>
					</el-input>
				</el-form-item>

				<!-- 上传头像 -->
				<el-form-item v-if="dialogAttribute.title == '新增店铺'" label="上传头像" prop="imgUrl">
					<el-upload class="avatar-uploader" action="/api/admin/common/upload" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						<img v-if="shops.imgUrl" :src="shops.imgUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>

				<!-- 状态 -->
				<el-form-item label="状态" prop="status">
					<el-select v-model="shops.status" placeholder="请选择状态">
						<el-option label="正常" :value="1" />
						<el-option label="禁用" :value="0" />
					</el-select>
				</el-form-item>
			</el-form>
		</Dialog>
		<div class="order-table-section">
			<div class="section-header">
				<el-button type="success" @click="addShop">新增店铺</el-button>
				<el-button type="danger" @click="deleteBatchShop">批量删除</el-button>
			</div>
			<el-card shadow="hover" class="table-card">
				<el-table :data="shopData" style="width: 100%" border stripe height="500px" empty-text="当前没有数据"
					v-loading="loading" @selection-change="handleSelectionChange" element-loading-text="数据加载中..."
					:header-cell-style="{background: '#f0f7ff', color: '#333'}">

					<el-table-column type="selection" width="55" />
					<el-table-column type="index" label="序号" width="60" />
					<el-table-column prop="username" label="账号" width="80" />
					<el-table-column prop="realName" label="注册人姓名" width="100" />
					<el-table-column prop="email" label="注册邮箱" width="160" />
					<el-table-column prop="phoneNumber" label="手机号" width="120" />

					<el-table-column prop="imgUrl" label="头像" width="135">
						<template #default="scope">
							<el-image :src="scope.row.imgUrl" style="width: 100px; height: 100px"
								:preview-src-list="[scope.row.imgUrl]" hide-on-click-modal preview-teleported />
						</template>
					</el-table-column>

					<el-table-column prop="role" label="账号角色" width="100">
						<template #default="scope">
							<el-tag :type="scope.row.role==0 ? 'success' : 'primary'" effect="plain">
								{{ scope.row.role==0 ? '站长' : '普通管理员' }}
							</el-tag>
						</template>
					</el-table-column>

					<el-table-column prop="lastLoginTime" label="上次登录时间" width="145" />
					<el-table-column prop="createdTime" label="创建时间" width="145" />
					<el-table-column prop="updatedTime" label="更新时间" width="145" />

					<el-table-column prop="status" label="账号状态" width="90">
						<template #default="scope">
							<el-tag :type="scope.row.status=='1' ? 'success' : 'danger'" effect="plain">
								{{ scope.row.status=='1' ? '正常' : '禁用' }}
							</el-tag>
						</template>
					</el-table-column>

					<el-table-column label="操作" fixed="right" width="300">
						<template #default="scope">
							<el-button type="primary" size="small" @click="updateShop(scope.row.id)" plain>
								<el-icon>
									<Edit />
								</el-icon>编辑
							</el-button>
							<el-button type="danger" size="small" @click="deleteShop(scope.row.id)" plain>
								<el-icon>
									<Delete />
								</el-icon>删除
							</el-button>
							<el-button v-if="scope.row.status=='1'" type="warning" size="small"
								@click="disableShop(scope.row)" plain>
								<el-icon>
									<Close />
								</el-icon>禁用
							</el-button>
							<el-button v-else type="success" size="small" @click="disableShop(scope.row)" plain>
								<el-icon>
									<Check />
								</el-icon>启用
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="pagination-container">
					<el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
						:total="pagination.total" :page-sizes="[10, 20, 30, 50]"
						layout="total, sizes, prev, pager, next, jumper" background />
				</div>
			</el-card>
		</div>

		<div style="margin-top: 20px;">
			<el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
				:page-sizes="[10,20,30,40]" background="true" layout="total, sizes, prev, pager, next, jumper"
				:total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<style scoped>
	/*
	表单
	*/
	.empty-tip {
		padding: 10px;
		text-align: center;
		color: #999;
	}

	.empty-tip p {
		margin-bottom: 10px;
	}

	/* 订单表格区域 */
	.order-table-section {
		margin-top: 30px;
	}

	.table-card {
		border-radius: 8px;
	}

	.amount-text {
		color: #ff7d00;
		font-weight: bold;
	}

	.remark-text {
		color: #666;
		font-size: 13px;
	}

	.no-remark {
		color: #999;
		font-style: italic;
		font-size: 13px;
	}

	.dish-list {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.dish-item {
		margin: 2px 0;
	}

	.pagination-container {
		margin-top: 20px;
		display: flex;
		justify-content: flex-end;
	}

	.order-manage-section {
		margin-top: 30px;
	}

	.section-header {
		display: flex;
		justify-content: left;
		align-items: center;
		margin-bottom: 20px;
	}

	.order-filter {
		display: flex;
		gap: 10px;
		align-items: center;
	}

	.order-cards-container {
		display: grid;
		grid-template-columns: repeat(6, 1fr);
		gap: 15px;
	}

	.order-card {
		border-radius: 8px;
		transition: all 0.3s;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.order-card:hover {
		transform: translateY(-3px);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.order-content {
		padding: 15px;
		text-align: center;
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.order-value {
		font-size: 24px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.order-title {
		font-size: 14px;
		margin-bottom: 10px;
		color: #666;
	}

	.order-icon {
		font-size: 30px;
		margin: 10px 0;
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.order-footer {
		font-size: 12px;
		color: #999;
	}

	.order-footer .up {
		color: #67c23a;
	}

	.order-footer .down {
		color: #f56c6c;
	}

	/* 响应式调整 */
	@media (max-width: 1600px) {
		.order-cards-container {
			grid-template-columns: repeat(3, 1fr);
		}
	}

	@media (max-width: 1200px) {
		.order-cards-container {
			grid-template-columns: repeat(2, 1fr);
		}
	}

	@media (max-width: 768px) {
		.order-cards-container {
			grid-template-columns: 1fr;
		}

		.section-header {
			flex-direction: column;
			align-items: flex-start;
			gap: 10px;
		}

		.order-filter {
			width: 100%;
		}
	}
</style>